import jwt
import datetime


class JWTUtil:
    # 密钥和算法
    SECRET_KEY = "gezhixuezhou"
    ALGORITHM = "HS256"

    @classmethod
    def gen_token(cls, claims: dict) -> str:
        """
        :param claims:
        :return: 生成jwt令牌
        """
        # 设置过期时间
        expire_time = datetime.datetime.now() + datetime.timedelta(hours=12)

        # 生成JWT令牌
        token = jwt.encode(
            payload={
                "claims": claims,
                "exp": expire_time
            },
            key=cls.SECRET_KEY,
            algorithm=cls.ALGORITHM
        )
        return token

    @classmethod
    def parse_token(cls, token: str) -> dict:
        """
        :param token:  用户的token
        :return:  返回用户信息
        """
        try:
            # 验证jwt令牌
            payload = jwt.decode(
                jwt=token,
                key=cls.SECRET_KEY,
                algorithms=[cls.ALGORITHM]
            )
            return payload.get("claims", {})
        except jwt.ExpiredSignatureError:
            raise Exception("token已经过期")
        except jwt.InvalidTokenError:
            raise Exception("无效的token")


if __name__ == "__main__":
    user_map = JWTUtil.parse_token(
        "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9"
        ".eyJjbGFpbXMiOnsiaWQiOjEsInVzZXJuYW1lIjoid2FuZ2JhIn0sImV4cCI6MTc0NjQ4NDE2MH0.57jfX-peAHiD0pbujPvW"
        "-x3aQgEGqQMC6Liu2vr-0cs")
    print(user_map)
